package interviewClassic150;

import java.util.HashMap;
import java.util.Map;

public class IsAnagram {
    public boolean isAnagram(String s, String t) {
        if (s.length() != t.length()) return false;

        //定义一个map来映射s中每个字母出现次数
        Map<Character,Integer> map = new HashMap<>();
        //遍历s
        for (int i = 0; i < s.length(); i++) {
            char curCh = s.charAt(i);
            int num = map.getOrDefault(curCh,0);
            map.put(curCh,num + 1);
        }
        //遍历t
        for (int i = 0; i < t.length(); i++) {
            char curCh = t.charAt(i);
            int num = map.getOrDefault(curCh,0);
            if (num == 0) return false;//这个字母在s中不存在，不为字母异位词，或者之前t中这个字母已经将s中的该字母抵扣完了
            if (num - 1 == 0) {
                map.remove(curCh);//消耗完了，从map中移除
                continue;
            }
            //未消耗完，则value-1
            map.put(curCh,num - 1);

        }

        return true;
    }
}
